import { useLocation } from "react-router-dom";
import { useMemo } from "react";
import { Role } from "../router/types";
import { findRouteByPath } from "../router/guards";
import { routes } from "../router/config";
import authService from "../services/auth";

/**
 * 路由角色与权限相关钩子
 * 根据当前路由路径获取相关角色与权限信息
 */
export function useRouteRole() {
  const location = useLocation();

  return useMemo(() => {
    const currentPath = location.pathname;

    // 查找当前路由配置
    const currentRoute = findRouteByPath(routes, currentPath);
    const currentUser = authService.getUser();

    // 获取路由所需角色
    const requiredRoles = currentRoute?.meta?.roles || [];

    // 获取路由所需权限
    const requiredPermissions = currentRoute?.meta?.permissions || [];

    // 检查当前用户是否满足角色要求
    const hasRequiredRole = currentRoute
      ? authService.hasRole(requiredRoles as Role[])
      : true;

    // 检查当前用户是否满足权限要求
    const hasRequiredPermission = currentRoute
      ? authService.hasPermission(requiredPermissions)
      : true;

    // 检查当前路由是否需要认证
    const requiresAuth = currentRoute?.meta?.requiresAuth ?? false;

    // 检查用户是否已认证
    const isAuthenticated = authService.getIsAuthenticated();

    return {
      // 路由相关
      currentPath,
      route: currentRoute,
      requiresAuth,

      // 角色与权限相关
      requiredRoles,
      requiredPermissions,
      hasRequiredRole,
      hasRequiredPermission,

      // 用户相关
      currentUser,
      isAuthenticated,
      userRoles: currentUser?.roles || [],
      userPermissions: currentUser?.permissions || [],

      // 工具函数
      checkPermission: authService.hasPermission.bind(authService),
      checkRole: authService.hasRole.bind(authService),
    };
  }, [location.pathname]);
}

export default useRouteRole;
